const baseUrl = "http://rinke.wicp.net:8089/";

const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join("/")} ${[
    hour,
    minute,
    second,
  ]
    .map(formatNumber)
    .join(":")}`;
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

const request = function (url, options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: options.method,
      data: options.method == "GET" ? undefined : JSON.stringify(options.data),
      header: {
        Authorization: "Bearer " + wx.getStorageSync("token"),
      },
      success: (res) => {
        if (res.statusCode == 500) {
          Toast(res.data.msg);
          reject(res.data.msg);
        } else {
          resolve(res);
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

module.exports = {
  formatTime,
  getApi(url) {
    return request(url, {
      method: "GET",
    });
  },
  postApi(url, data) {
    return request(url, {
      method: "POST",
      data,
    });
  },
  putApi(url, data) {
    return request(url, {
      method: "PUT",
      data,
    });
  },
};
